package com.jz.community.moduleshopping.orderList.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.bean.baseCommInfo.PageInfo;
import com.jz.community.basecomm.utils.ArrayUtil;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.orderDetail.bean.OrderEvent;
import com.jz.community.moduleshopping.orderDetail.ui.OrderDetailActivity;
import com.jz.community.moduleshopping.orderList.adapter.NewOrderListAdapter;
import com.jz.community.moduleshopping.orderList.bean.CouponInfoOrderBean;
import com.jz.community.moduleshopping.orderList.bean.NewOrderListInfo;
import com.jz.community.moduleshopping.orderList.enums.OrderStatusType;
import com.jz.community.moduleshopping.orderList.presenter.OrderPresenter;
import com.jz.community.moduleshopping.orderList.task.CouponInfoOrderTask;
import com.jz.community.moduleshopping.orderList.view.OrderView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony on 2018/4/26.
 * <p>
 * 订单列表
 */
public class OrderListFragment extends BaseMvpFragment<OrderView.View, OrderPresenter> implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, OrderView.View {
    @BindView(R2.id.fragment_order_list)
    RecyclerView fragmentOrderList;
    @BindView(R2.id.fragment_order_refresh)
    SmartRefreshLayout fragmentOrderRefresh;
    @BindView(R2.id.fragment_order_layout)
    LinearLayout fragmentOrderLayout;
    private int type;
    private String orderStatus;//订单状态
    private int page = 0;//页数
    private NewOrderListAdapter newOrderListAdapter;
    private List<NewOrderListInfo.EmbeddedBean.OrderInfoesBean> orderList = new ArrayList<>();
    private Observable<ToLoginEvent> toLoginRxBusObser;
    private int[] orderType = new int[]{0, 1, 2, 3, 4}; //Title显示类型
    private boolean mIsRefresh;
    private PageInfo pageBean;

    public static OrderListFragment newInstance(int mType) {
        OrderListFragment orderFragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("orderType", mType);
        orderFragment.setArguments(bundle);
        return orderFragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shopping_fragment_order;
    }

    @Override
    protected OrderPresenter createPresenter() {
        return new OrderPresenter(this);
    }

    @Override
    protected void initVisible() {
        super.initVisible();
    }

    @Override
    protected void initView() {
        type = getArguments().getInt("orderType");
        if (type == orderType[0]) {
            //全部订单
            orderStatus = "";
        } else if (type == orderType[1]) {
            //待付款
            orderStatus = OrderStatusType.ORDER_UNPAID_PAY_STATUS.getOrderStatus();
        } else if (type == orderType[2]) {
            //待发货
            orderStatus = OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus() + "," + OrderStatusType.ORDER_DELIVERY_STATUS.getOrderStatus();
        } else if (type == orderType[3]) {
            //待收货
            orderStatus = OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus();
        } else if (type == orderType[4]) {
            //待评价
            orderStatus = OrderStatusType.ORDER_SUCCESS_STATUS.getOrderStatus();
        }
        registerLoginByRxBus();
        registerOrderEvent();
    }

    @Override
    protected void initDatas() {
        handleBindAdapter();
    }

    /**
     * 登录处理
     */
    @SuppressLint("CheckResult")
    private void registerLoginByRxBus() {
        toLoginRxBusObser = RxBus.getInstance().register(ToLoginEvent.toLoginRxBusTag, ToLoginEvent.class);
        toLoginRxBusObser.subscribe(toLoginEvent -> {
            handleData(toLoginEvent);
        }, throwable -> {
        });
    }

    /**
     * 订单列表
     */
    @SuppressLint("CheckResult")
    private void registerOrderEvent() {
        RxBus.getInstance().register(OrderEvent.toOrderRxBusTag, OrderEvent.class).subscribe(new Consumer<OrderEvent>() {
            @Override
            public void accept(OrderEvent orderEvent) throws Exception {
                if (orderEvent.getOrderType() == OrderEvent.ORDER_TYPE_1) {
                    page = 0;
                    loadOrderData(true, true);
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });
    }

    private void handleData(ToLoginEvent toLoginEvent) {
        if (toLoginEvent.isToPwdLogin() || toLoginEvent.isToWeChatLogin()) {
            loadOrderData(true, true);
        } else {
            newOrderListAdapter = new NewOrderListAdapter(new ArrayList());
            fragmentOrderList.setAdapter(newOrderListAdapter);
            newOrderListAdapter.setEmptyView(noLoginView(fragmentOrderList));
        }
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        if (BaseUserUtils.getIsLogin(getActivity())) {
            loadOrderData(true, true);
        } else {
            newOrderListAdapter.setEmptyView(noLoginView(fragmentOrderList));
        }
    }

    private void handleBindAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        fragmentOrderRefresh.setOnRefreshListener(this);
        fragmentOrderList.setLayoutManager(layoutManager);
        newOrderListAdapter = new NewOrderListAdapter(orderList);
        newOrderListAdapter.setEnableLoadMore(false);
        newOrderListAdapter.setOnLoadMoreListener(this, fragmentOrderList);
        fragmentOrderList.setAdapter(newOrderListAdapter);
    }

    @Override
    public void onLoadMoreRequested() {
        loadOrderData(false, false);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        page = 0;
        loadOrderData(true, false);
        newOrderListAdapter.setEnableLoadMore(false);
    }

    private void setData(boolean isRefresh, List data) {

        page++;

        if (isRefresh) {
            newOrderListAdapter.setNewData(data);
        } else {
            newOrderListAdapter.addData(data);
        }

        if (pageBean.getTotalPages() <= page) {
            newOrderListAdapter.loadMoreEnd();
        } else {
            newOrderListAdapter.loadMoreComplete();
        }
    }

    private void loadOrderData(boolean isRefresh, boolean needDialog) {
        mIsRefresh = isRefresh;
        mPresenter.getOrderInfo(orderStatus, ConverterUtils.toString(page), needDialog);
    }

    /**
     * 加载订单列表
     *
     * @param orderListBean
     */
    private void loadOrderListInfo(boolean isRefresh, NewOrderListInfo orderListBean) {
        pageBean = orderListBean.getPage();
        orderList = orderListBean.get_embedded().getOrderInfoes();
        setData(isRefresh, orderList);
        //查询待收货订单列表页是否有可领取的优惠券
        queryOrderListCoupon();

        newOrderListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(getContext(), OrderDetailActivity.class);
            intent.putExtra("orderId", newOrderListAdapter.getData().get(position).getOrderId());
            intent.putExtra("couponMark", newOrderListAdapter.getData().get(position).getCouponMark());
            getActivity().startActivity(intent);
        });
    }


    private void queryOrderListCoupon() {
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < newOrderListAdapter.getData().size(); i++) {
            ids.add(newOrderListAdapter.getData().get(i).getOrderId());
        }
        new CouponInfoOrderTask(getActivity(), o -> {
            List<CouponInfoOrderBean> couponInfoList = (List<CouponInfoOrderBean>) o;
            if (Preconditions.isNullOrEmpty(couponInfoList)) {
                return;
            }
            for (int i = 0; i < couponInfoList.size(); i++) {
                for (int j = 0; j < newOrderListAdapter.getData().size(); j++) {
                    if (couponInfoList.get(i).getOrderId().equals(newOrderListAdapter.getData().get(j).getOrderId())) {
                        newOrderListAdapter.getData().get(j).setCouponMark(couponInfoList.get(i).getMark());
                    }
                }
            }
            newOrderListAdapter.notifyDataSetChanged();
        }).execute(ArrayUtil.listToString(ids));
    }

    private void unRegisterLoginByRxBus() {
        RxBus.getInstance().unregister(ToLoginEvent.toLoginRxBusTag, toLoginRxBusObser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterLoginByRxBus();
    }

    @Override
    public void showOrderInfo(NewOrderListInfo newOrderListInfo) {
        if (!Preconditions.isNullOrEmpty(newOrderListInfo) && !Preconditions.isNullOrEmpty(newOrderListInfo.get_embedded().getOrderInfoes())) {
            fragmentOrderRefresh.finishRefresh();
            loadOrderListInfo(mIsRefresh, newOrderListInfo);
        } else {
            fragmentOrderRefresh.finishRefresh();
            newOrderListAdapter = new NewOrderListAdapter(new ArrayList());
            fragmentOrderList.setAdapter(newOrderListAdapter);
            newOrderListAdapter.setEmptyView(noDataView(fragmentOrderList, "暂无订单！"));
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }
}
